﻿using BootstrapAdmin.DataAccess.Models;
using BootstrapAdmin.DataAccess.Models.Production;
using BootstrapAdmin.Web.Core.Models;
using BootstrapAdmin.Web.Core.Services;
using PetaPoco;

namespace BootstrapAdmin.DataAccess.PetaPoco.Services;

internal sealed class MaterialService : IMaterialService
{
    private readonly IDBManager _dbManager;

    public MaterialService(IDBManager db) => _dbManager = db;

    public async Task<ApiResult> SaveCriticalMaterialAsync(ApiData data)
    {
        var barcode = data.GetValue<string>("PLC_Critical_Material_Barcode");
        var index = data.GetValue<int>("PLC_Critical_Material_Index");
        if (string.IsNullOrWhiteSpace(barcode))
        {
            return ApiResult.Error(ErrorCode.ErrEmptyOfBarcode);
        }

        try
        {
            using var db = _dbManager.Create();

            // 1. 校验物料是否是重复使用
            // 2. 校验 BOM

            Sql sql = new();
            sql.Where("Station = @0", data.Schema.Station);
            var info = await db.FirstOrDefaultAsync<InboundInfo>(sql);
            if (info == null)
            {
                return ApiResult.Error(ErrorCode.ErrNullOfInbound);
            }

            TrackMaterial trackMaterial = new()
            {
                Station = data.Schema.Station,
                SN = info!.SN,
                Barcode = barcode,
                CreatedAt = DateTime.Now,
            };

            await db.InsertAsync(trackMaterial);

        }
        catch (Exception ex)
        {
            return ApiResult.Error(ex.Message);
        }

        return ApiResult.Ok();
    }

    public Task<ApiResult> SaveBactchMaterialAsync(ApiData data)
    {
        return Task.FromResult(ApiResult.Ok());
    }
}
